package com.cloudpolice.door.receive;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudpolice.door.feignInterface.*;
import com.cloudpolice.door.model.*;
import com.cloudpolice.door.model.InPutParam.FaceLogInsertInParam;
import com.cloudpolice.door.model.InPutParam.FaceLogSubBaseInsertInParam;
import com.cloudpolice.door.model.InPutParam.FaceLogSubInsertInParam;
import com.cloudpolice.door.service.FaceLogService;
import com.cloudpolice.door.unit.GetPropertiesClass;
import com.google.gson.Gson;
import lh.model.ResultVO;
import lh.toolclass.LhClass;
import lh.units.ResultStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lianghao
 * @create 2019-12-15 13:36
 */
@Component
@RabbitListener(queues = "doorLogTest")
public class ReceiveRabbitMQ {
    @Autowired
    FaceLogService faceLogService;
    @Autowired
    GetPropertiesClass getPropertiesClass;
    @Autowired
    EquipmentInterFace equipmentInterFace;
    @Autowired
    Gson gson;

    @Autowired
    EquipmentSiteInterFace equipmentSiteInterFace;
    @Autowired
    PersonInterFace personInterFace;
    @Autowired
    RoomInterFace roomInterFace;
    @Autowired
    MainSubUseInterFace mainSubUseInterFace;


    private static Logger logger = LoggerFactory.getLogger(ReceiveRabbitMQ.class);

    @RabbitHandler()
    public void getPicId(String mqModel) {
        if (mqModel == null || mqModel.isEmpty()) {
            return;
        }
//        System.out.println(mqModel);
        if (mqModel.contains("-")) {
            String mainFaceLog = mqModel.split("-")[0];
            String subFaceLogList = mqModel.split("-")[1];

            FaceLogInsertInParam faceLogBaseInsertInParam = JSONObject.parseObject(mainFaceLog, FaceLogInsertInParam.class);

            List<FaceLogSubBaseInsertInParam> faceLogSubBaseInsertInParams = new ArrayList<>();
            if (subFaceLogList != null && !subFaceLogList.isEmpty()) {
                final List list = gson.fromJson(subFaceLogList, List.class);
                for (Object row : list) {
                    FaceLogSubBaseInsertInParam faceLogSubBaseInsertInParam = gson.fromJson(row.toString(), FaceLogSubBaseInsertInParam.class);
                    if (faceLogSubBaseInsertInParam != null) {
                        faceLogSubBaseInsertInParams.add(faceLogSubBaseInsertInParam);
                    }
                }
            }
            this.insertDownDoorRecord(faceLogBaseInsertInParam, faceLogSubBaseInsertInParams);
//            EquipmentSiteModel siteId1 = this.getSiteId(faceLogBaseInsertInParam.getSn());
//            System.out.println(JSON.toJSONString(siteId1));
        }
    }


    /**
     * 离线、在线，首次提交数据库，主表方法
     *
     * @param faceLogBaseInsertInParam
     * @return
     */
    private FaceLogInsertInParam getFaceLogInsertInParam(
            FaceLogInsertInParam faceLogBaseInsertInParam) {
        FaceLogInsertInParam faceLogInsertInParam = new FaceLogInsertInParam();
        faceLogInsertInParam.setId(faceLogBaseInsertInParam.getId());
        faceLogInsertInParam.setSn(faceLogBaseInsertInParam.getSn());
        faceLogInsertInParam.setBasePicId(faceLogBaseInsertInParam.getBasePicId());
        faceLogInsertInParam.setPersonId(faceLogBaseInsertInParam.getPersonId());
        faceLogInsertInParam.setFaceBasePicId(faceLogBaseInsertInParam.getFaceBasePicId());
        faceLogInsertInParam.setOpenType(faceLogBaseInsertInParam.getOpenType());
        faceLogInsertInParam.setPersonType(faceLogBaseInsertInParam.getPersonType());
        faceLogInsertInParam.setAiType(faceLogBaseInsertInParam.getAiType());
        faceLogInsertInParam.setRemark(faceLogBaseInsertInParam.getRemark());
        faceLogInsertInParam.setCardId(faceLogBaseInsertInParam.getCardId());
        faceLogInsertInParam.setDoorTime(faceLogBaseInsertInParam.getDoorTime());
        faceLogInsertInParam.setStopSign(faceLogBaseInsertInParam.getStopSign());
        faceLogInsertInParam.setAiClass(faceLogBaseInsertInParam.getAiClass());  //比对方式（0：离线；1：在线）

        //根据PersonType判断人员的身份,分为用户type=0,或者其他(物业人员,警务人员)
        if (faceLogBaseInsertInParam.getPersonType() == 0) { //如果是住户
            //根据personId调用information-mucon粒子层,得到人的信息
            PersonVO person = this.getPerson(faceLogBaseInsertInParam.getPersonId());
            if (person != null) {
                faceLogInsertInParam.setSex(person.getSex());
                faceLogInsertInParam.setMobile(person.getMobile());
                faceLogInsertInParam.setPersonName(person.getPersonName());
                faceLogInsertInParam.setBlackType(person.getBlackType());
                faceLogInsertInParam.setBlackTag(person.getBlackTag());
            }
        }
        if (faceLogBaseInsertInParam.getPersonType() == 1) { //如果是物业人员
            //根据personId调用user-mucon粒子层,得到物业人员信息
            MainSubUseModel mainSubUseModel = this.getMainSubUseModel(faceLogBaseInsertInParam.getPersonId());
            if (mainSubUseModel != null) {
                faceLogInsertInParam.setSex("0");
                faceLogInsertInParam.setMobile(mainSubUseModel.getMobile());
                faceLogInsertInParam.setPersonName(mainSubUseModel.getUseName());
                faceLogInsertInParam.setBlackType("");
                faceLogInsertInParam.setBlackTag("");
            }
        }

        //根据设备sn号,调用equipment-mucon粒子层,拿到设备基本信息
        EquipmentModel equipment = this.getEquipment(faceLogBaseInsertInParam.getSn());
        if (equipment != null) {
            faceLogInsertInParam.setEquipmentType(equipment.getEquipmentType());
            faceLogInsertInParam.setEquipmentName(equipment.getEquipmentName());
        }

        //根据设备sn号,调用equipment-mucon粒子层,拿到设备绑定的位置信息
        EquipmentSiteModel equipmentSiteModel = this.getSiteId(faceLogBaseInsertInParam.getSn());
        if (equipmentSiteModel != null) {
            //根据设备siteId号,调用information-mucon粒子层,拿到房屋信息
            RoomDto roomDto = new RoomDto();
            if (equipmentSiteModel.getRoomType() == 3) {  //如果是单元机
                roomDto.setId(equipmentSiteModel.getSiteId());
                roomDto.setType("3");
                RoomVO room = this.getRoom(roomDto);
                if (room != null) {
                    faceLogInsertInParam.setCommunityId(room.getCommunityId());
                    faceLogInsertInParam.setCommunityName(room.getCommunityName());
                    faceLogInsertInParam.setPeriodId(room.getPeriodsId());
                    faceLogInsertInParam.setPeriodName(room.getPeriods());
                    faceLogInsertInParam.setBuildId(room.getBuildingId());
                    faceLogInsertInParam.setBuildName(room.getBuilding());
                    faceLogInsertInParam.setUnitId(room.getElementId());
                    faceLogInsertInParam.setUnitName(room.getElement());
                    if (room.getXCoordinates() != null)
                        faceLogInsertInParam.setLatitude(Float.parseFloat(room.getXCoordinates()));
                    if (room.getYCoordinates() != null)
                        faceLogInsertInParam.setLongitude(Float.parseFloat(room.getYCoordinates()));
                }
            } else if (equipmentSiteModel.getRoomType() == 5) {  //如果是围墙机:通道
                roomDto.setId(equipmentSiteModel.getSiteId());
                roomDto.setType("2");
                RoomVO room = this.getRoom(roomDto);
                if (room != null) {
                    faceLogInsertInParam.setCommunityId(room.getCommunityId());
                    faceLogInsertInParam.setCommunityName(room.getCommunityName());
                    faceLogInsertInParam.setPeriodId(room.getPeriodsId());
                    faceLogInsertInParam.setPeriodName(room.getPeriods());
                    faceLogInsertInParam.setAccessId(room.getAccessId());
                    faceLogInsertInParam.setAccessName(room.getAccessName());
                    if (room.getXCoordinates() != null)
                        faceLogInsertInParam.setLatitude(Float.parseFloat(room.getXCoordinates()));
                    if (room.getYCoordinates() != null)
                        faceLogInsertInParam.setLongitude(Float.parseFloat(room.getYCoordinates()));
                }
            }
        }
    /*    if (afterSign) {
            faceLogInsertInParam.setOpenType(0);
            faceLogInsertInParam.setAiAfterType(getPropertiesClass.getAiArithmeticName());
            faceLogInsertInParam.setDoorTime(new Date());
        } else {
            faceLogInsertInParam.setCardId(faceLogBaseInsertInParam.getCardId());
            faceLogInsertInParam.setOpenType(faceLogBaseInsertInParam.getOpenType());
            faceLogInsertInParam.setAiType(faceLogBaseInsertInParam.getAiType());
            faceLogInsertInParam.setDoorTime(faceLogBaseInsertInParam.getDoorTime());
        }*/
        return faceLogInsertInParam;
    }

    /**
     * 离线、在线，首次提交数据库，从表方法
     *
     * @param faceLogSubBaseInsertInParam
     * @param index
     * @param mainId
     * @return
     */
    private FaceLogSubInsertInParam getFaceLogSubInsertInParam(FaceLogSubBaseInsertInParam faceLogSubBaseInsertInParam
            , int index
            , String mainId) {
        FaceLogSubInsertInParam faceLogSubInsertInParam = new FaceLogSubInsertInParam();
        faceLogSubInsertInParam.setId(LhClass.getFaceSub(Short.valueOf(getPropertiesClass.getPort())));
        faceLogSubInsertInParam.setMainId(mainId);
        faceLogSubInsertInParam.setSortNo(index);
        faceLogSubInsertInParam.setLeftDown(faceLogSubBaseInsertInParam.getLeftDown());
        faceLogSubInsertInParam.setLeftUp(faceLogSubBaseInsertInParam.getLeftUp());
        faceLogSubInsertInParam.setReality(faceLogSubBaseInsertInParam.getReality());
        faceLogSubInsertInParam.setRigthDown(faceLogSubBaseInsertInParam.getRigthDown());
        faceLogSubInsertInParam.setRigthUp(faceLogSubBaseInsertInParam.getRigthUp());
        faceLogSubInsertInParam.setSmallFacePicId(faceLogSubBaseInsertInParam.getSmallFacePicId());
        faceLogSubInsertInParam.setStandard(faceLogSubBaseInsertInParam.getStandard());
        faceLogSubInsertInParam.setSuccess(faceLogSubBaseInsertInParam.getSuccess());
        //识别穿戴功能,暂时存入默认值
        faceLogSubInsertInParam.setHatSign(-1);
        faceLogSubInsertInParam.setMaskSign(-1);
        faceLogSubInsertInParam.setGlassesSign(-1);
        faceLogSubInsertInParam.setScarfSign(-1);
        return faceLogSubInsertInParam;
    }

    private ResultVO insertDownDoorRecord(FaceLogInsertInParam faceLogBaseInsertInParam
            , List<FaceLogSubBaseInsertInParam> faceLogSubBaseInsertInParams) {
        FaceLogInsertInParam faceLogInsertInParam = getFaceLogInsertInParam(
                faceLogBaseInsertInParam);

        List<FaceLogSubInsertInParam> faceLogSubInsertInParams = new ArrayList<>();
        if (faceLogSubBaseInsertInParams != null) {
            int index = 0;
            for (FaceLogSubBaseInsertInParam faceLogSubBaseInsertInParam :
                    faceLogSubBaseInsertInParams) {
                FaceLogSubInsertInParam faceLogSubInsertInParam = getFaceLogSubInsertInParam(faceLogSubBaseInsertInParam
                        , index++
                        , faceLogInsertInParam.getId());
                faceLogSubInsertInParams.add(faceLogSubInsertInParam);
            }
        }
        int resultCount = faceLogService.insertAllFaceLog(faceLogInsertInParam, faceLogSubInsertInParams);
        if (resultCount > 0) {
//            UpdateFaceLogThread updateFaceLogThread = new UpdateFaceLogThread(faceLogInsertInParam);
//            updateFaceLogThread.run();
            return ResultStruct.success("上传成功", resultCount);
        } else
            return ResultStruct.error("上传失败", ResultVO.class, null);
    }

    //根据设备sn号,调用equipment-mucon粒子层,拿到设备绑定的位置信息
    private EquipmentSiteModel getSiteId(String sn) {
        ResultVO equipmentSite = equipmentInterFace.selectEquipmentSiteBySn(sn);
        EquipmentSiteModel equipmentSiteModel;
        EquipmentSiteModel equipmentSiteModelx = new EquipmentSiteModel();
        if (equipmentSite != null) {
            if (equipmentSite.getCode() == 0) {
                String equipmentSiteData = JSON.toJSONString(equipmentSite.getData());
                JSONArray objects = JSON.parseArray(equipmentSiteData);
                for (Object object : objects) {
                    String s = JSON.toJSONString(object);
                    equipmentSiteModel = JSONObject.parseObject(s, EquipmentSiteModel.class);
                    if (equipmentSiteModel.getRoomType() == 3) {
                        equipmentSiteModelx.setSn(equipmentSiteModel.getSn());
                        equipmentSiteModelx.setSiteId(equipmentSiteModel.getSiteId());
                        equipmentSiteModelx.setRoomType(equipmentSiteModel.getRoomType());
                    }
                    if (equipmentSiteModel.getRoomType() == 5) {
                        equipmentSiteModelx.setSn(equipmentSiteModel.getSn());
                        equipmentSiteModelx.setSiteId(equipmentSiteModel.getSiteId());
                        equipmentSiteModelx.setRoomType(equipmentSiteModel.getRoomType());
                    }
                }
            }
        }
        return equipmentSiteModelx;
    }


  /*  private EquipmentSiteModel getSiteId(String sn){
        ResultVO equipmentSite = equipmentSiteInterFace.getEquipmentSite(sn);
        EquipmentSiteModel equipmentSiteModel = new EquipmentSiteModel();
        if (equipmentSite !=null) {
            if (equipmentSite.getCode() == 0) {
                String equipmentSiteData = JSON.toJSONString(equipmentSite.getData());
                equipmentSiteModel = JSONObject.parseObject(equipmentSiteData, EquipmentSiteModel.class);
            }
        }
        return equipmentSiteModel;
    }*/

    //根据personId调用information-mucon粒子层,得到人的信息
    private PersonVO getPerson(String personId) {
        ResultVO personById = personInterFace.getPersonById(personId);
        PersonVO person = new PersonVO();
        if (personById != null) {
            if (personById.getCode() == 0) {
                String personData = JSON.toJSONString(personById.getData());
                person = JSONObject.parseObject(personData, PersonVO.class);
            }
        }
        return person;
    }

    //根据设备siteId号,调用information-mucon粒子层,拿到房屋信息
    private MainSubUseModel getMainSubUseModel(String personId) {
        ResultVO getMainSubUseById = mainSubUseInterFace.selectMainSubUseById(personId);
        MainSubUseModel mainSubUseModel = new MainSubUseModel();
        if (getMainSubUseById.getCode() == 0) {
            String getMainSubUseByIdData = JSON.toJSONString(getMainSubUseById.getData());
            mainSubUseModel = JSONObject.parseObject(getMainSubUseByIdData, MainSubUseModel.class);
        }
        return mainSubUseModel;
    }

    //根据设备siteId号,调用information-mucon粒子层,拿到房屋信息
    private RoomVO getRoom(RoomDto roomDto) {
        ResultVO getRoom = roomInterFace.getRoom(roomDto);
        RoomVO room = new RoomVO();
        if (getRoom.getCode() == 0) {
            String roomData = JSON.toJSONString(getRoom.getData());
            room = JSONObject.parseObject(roomData, RoomVO.class);
        }
        return room;
    }

    //根据设备sn号,调用equipment-mucon粒子层,拿到设备基本信息
    private EquipmentModel getEquipment(String sn) {
        ResultVO getRoom = equipmentInterFace.SelectEquipmentBySn(sn, false);
        EquipmentModel equipment = new EquipmentModel();
        if (getRoom.getCode() == 0) {
            String equipmentData = JSON.toJSONString(getRoom.getData());
            equipment = JSONObject.parseObject(equipmentData, EquipmentModel.class);
        }
        return equipment;
    }



 /*   //根据aiClass判断是在线还是离线
    private boolean getAiClass(String aiClass) {
        boolean isAiClass = false;
        if (aiClass.equals("0"))
            isAiClass = false;
        if (aiClass.equals("1"))
            isAiClass = true;
        return isAiClass;
    }*/



  /*      private class UpdateFaceLogThread implements Runnable {
            private FaceLogInsertInParam faceLogInsertInParam;

            private UpdateFaceLogThread(FaceLogInsertInParam faceLogInsertInParam) {
                this.faceLogInsertInParam = faceLogInsertInParam;
            }

            @Override
            public void run() {
                String errorInfo = "未找到冗余信息：";
                boolean updateSign = true;
                FaceLogInsertInParam faceLogInsertInParamNew = new FaceLogInsertInParam();
                faceLogInsertInParamNew.setId(faceLogInsertInParam.getId());

                System.out.println("getPersonId:" + faceLogInsertInParam.getPersonId());
                faceLogInsertInParamNew.setSex("0");
                faceLogInsertInParamNew.setMobile("13972342314");
                faceLogInsertInParamNew.setPersonName("PersonName1");
                faceLogInsertInParamNew.setBlackType("BlackType");
                faceLogInsertInParamNew.setBlackTag("BlackTag");

                if (updateSign) {
                    final ResultVO resultVOEquip = equipmentInterFace.SelectEquipmentBySn(faceLogInsertInParam.getSn(), false);
                    updateSign = updateSign && (resultVOEquip.getCode() == 0 ? true : false);
                    if (updateSign) {
                        final EquipmentModel equipmentModel = gson.fromJson(resultVOEquip.getData().toString(), EquipmentModel.class);
                        faceLogInsertInParamNew.setEquipmentName(equipmentModel.getEquipmentName());
                        faceLogInsertInParamNew.setEquipmentType(equipmentModel.getEquipmentType());
                    } else
                        errorInfo += resultVOEquip.getMsg();
                }

                if (updateSign) {
                    final ResultVO resultVOEquipSite = equipmentInterFace.selectEquipmentSiteBySn(faceLogInsertInParam.getSn());
                    updateSign = updateSign && (resultVOEquipSite.getCode() == 0 ? true : false);
                    if (updateSign) {
                        final List list = gson.fromJson(resultVOEquipSite.getData().toString(), List.class);
                        for (Object row :
                                list) {
                            final EquipmentSiteModel equipmentSiteModel = gson.fromJson(row.toString(), EquipmentSiteModel.class);
                            switch (equipmentSiteModel.getRoomType()) {
                                case 0:
                                    faceLogInsertInParamNew.setCommunityId(equipmentSiteModel.getSiteId());//场所
                                    break;
                                case 1:
                                    faceLogInsertInParamNew.setPeriodId(equipmentSiteModel.getSiteId());//区域
                                    break;
                                case 2:
                                    faceLogInsertInParamNew.setBuildId(equipmentSiteModel.getSiteId());//楼栋
                                    break;
                                case 3:
                                    faceLogInsertInParamNew.setUnitId(equipmentSiteModel.getSiteId());//单元
                                    break;
                                default:
                                    faceLogInsertInParamNew.setAccessId(equipmentSiteModel.getSiteId());//通道
                                    break;
                            }
                        }
                    } else {
                        errorInfo += resultVOEquipSite.getMsg();
                    }
                }
                faceLogInsertInParamNew.setCommunityName("ComName");
                faceLogInsertInParamNew.setPeriodName("PeroidName");
                faceLogInsertInParamNew.setBuildName("BuildName");
                faceLogInsertInParamNew.setUnitName("UnitName");
                faceLogInsertInParamNew.setAccessName("AccessName1");

                faceLogInsertInParamNew.setLatitude((float) 23.3245324);
                faceLogInsertInParamNew.setLongitude((float) 3435.4564);


                if (updateSign)
                    faceLogInsertInParamNew.setRemark("ThreadOver");
                else
                    faceLogInsertInParamNew.setRemark(errorInfo);

                faceLogService.updateFaceLogById(faceLogInsertInParamNew);
            }
    }*/
}
